<template>
    <div class="quality-list">
      <div class="page-header">
        <div class="header-left">
          <h2>质量检测记录</h2>
          <p>管理商品质量检测记录，确保食品安全</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新增检测
          </el-button>
          <el-button type="success" @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
      </div>
  
      <div class="page-content">
        <!-- 搜索和筛选 -->
        <div class="search-section">
          <el-form :model="searchForm" inline>
            <el-form-item label="检测编号">
              <el-input
                v-model="searchForm.inspectionCode"
                placeholder="请输入检测编号"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="商品名称">
              <el-input
                v-model="searchForm.productName"
                placeholder="请输入商品名称"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="检测类型">
              <el-select
                v-model="searchForm.inspectionType"
                placeholder="请选择检测类型"
                clearable
                style="width: 150px"
              >
                <el-option label="常规检测" value="routine" />
                <el-option label="专项检测" value="special" />
                <el-option label="复检" value="recheck" />
                <el-option label="抽检" value="sampling" />
              </el-select>
            </el-form-item>
            <el-form-item label="检测结果">
              <el-select
                v-model="searchForm.result"
                placeholder="请选择结果"
                clearable
                style="width: 120px"
              >
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
                <el-option label="待定" value="待定" />
              </el-select>
            </el-form-item>
            <el-form-item label="检测状态">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
              >
                <el-option label="进行中" value="processing" />
                <el-option label="已完成" value="completed" />
                <el-option label="已审核" value="reviewed" />
                <el-option label="已发布" value="published" />
              </el-select>
            </el-form-item>
            <el-form-item label="检测日期">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 250px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="resetSearch">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
  
        <!-- 统计卡片 -->
        <div class="statistics-section">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon total">
                    <el-icon><Document /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{ statistics.total }}</div>
                    <div class="stat-label">总检测数</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon passed">
                    <el-icon><Check /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{ statistics.passed }}</div>
                    <div class="stat-label">合格数</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon failed">
                    <el-icon><Close /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{ statistics.failed }}</div>
                    <div class="stat-label">不合格数</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon rate">
                    <el-icon><TrendCharts /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{ statistics.passRate }}%</div>
                    <div class="stat-label">合格率</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
  
        <!-- 质量检测记录列表 -->
        <el-table
          :data="qualityRecords"
          v-loading="loading"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="inspectionCode" label="检测编号" width="150" />
          <el-table-column prop="productName" label="商品名称" min-width="150" />
          <el-table-column prop="batchNumber" label="生产批次" width="120" />
          <el-table-column prop="inspectionType" label="检测类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getInspectionTypeTag(row.inspectionType)">
                {{ getInspectionTypeText(row.inspectionType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="inspector" label="检测员" width="100" />
          <el-table-column prop="inspectionDate" label="检测日期" width="120" />
          <el-table-column prop="totalTests" label="检测项目" width="100" />
          <el-table-column prop="overallResult" label="检测结果" width="100">
            <template #default="{ row }">
              <el-tag :type="getResultType(row.overallResult)">
                {{ row.overallResult }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="passRate" label="合格率" width="100">
            <template #default="{ row }">
              <el-progress
                :percentage="parseFloat(row.passRate)"
                :color="getPassRateColor(row.passRate)"
                :stroke-width="8"
              />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="viewDetail(row)">
                  <el-icon><View /></el-icon>
                  查看详情
                </el-button>
                <el-button type="warning" size="small" @click="editRecord(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="deleteRecord(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
  
      <!-- 新增检测对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="新增质量检测"
        width="800px"
        @close="resetForm"
      >
        <el-form
          ref="qualityForm"
          :model="formData"
          :rules="rules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="检测编号" prop="inspectionCode">
                <el-input
                  v-model="formData.inspectionCode"
                  placeholder="请输入检测编号"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检测类型" prop="inspectionType">
                <el-select
                  v-model="formData.inspectionType"
                  placeholder="请选择检测类型"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="常规检测" value="routine" />
                  <el-option label="专项检测" value="special" />
                  <el-option label="复检" value="recheck" />
                  <el-option label="抽检" value="sampling" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品" prop="productId">
                <el-select
                  v-model="formData.productId"
                  placeholder="请选择商品"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="product in products"
                    :key="product.id"
                    :label="`${product.name} (${product.code})`"
                    :value="product.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产批次" prop="batchNumber">
                <el-input
                  v-model="formData.batchNumber"
                  placeholder="请输入生产批次"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="检测员" prop="inspector">
                <el-input
                  v-model="formData.inspector"
                  placeholder="请输入检测员姓名"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检测日期" prop="inspectionDate">
                <el-date-picker
                  v-model="formData.inspectionDate"
                  type="date"
                  placeholder="选择检测日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { defineComponent, ref, reactive, computed, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Download, Search, Refresh, View, Edit, Delete, Document, Check, Close, TrendCharts } from '@element-plus/icons-vue'
  
  export default defineComponent({
    name: 'QualityList',
    components: {
      Plus,
      Download,
      Search,
      Refresh,
      View,
      Edit,
      Delete,
      Document,
      Check,
      Close,
      TrendCharts
    },
    setup() {
      const router = useRouter()
      const loading = ref(false)
      const submitLoading = ref(false)
      const dialogVisible = ref(false)
      const currentPage = ref(1)
      const pageSize = ref(20)
      const total = ref(0)
      const selectedRecords = ref([])
      
      const qualityForm = ref(null)
      
      // 搜索表单
      const searchForm = reactive({
        inspectionCode: '',
        productName: '',
        inspectionType: '',
        result: '',
        status: '',
        dateRange: []
      })
      
      // 新增表单数据
      const formData = reactive({
        inspectionCode: '',
        inspectionType: '',
        productId: null,
        batchNumber: '',
        inspector: '',
        inspectionDate: ''
      })
      
      // 表单验证规则
      const rules = {
        inspectionCode: [
          { required: true, message: '请输入检测编号', trigger: 'blur' }
        ],
        inspectionType: [
          { required: true, message: '请选择检测类型', trigger: 'change' }
        ],
        productId: [
          { required: true, message: '请选择商品', trigger: 'change' }
        ],
        batchNumber: [
          { required: true, message: '请输入生产批次', trigger: 'blur' }
        ],
        inspector: [
          { required: true, message: '请输入检测员', trigger: 'blur' }
        ],
        inspectionDate: [
          { required: true, message: '请选择检测日期', trigger: 'change' }
        ]
      }
      
      // 模拟商品数据
      const products = ref([
        { id: 1, name: '有机苹果', code: 'P001' },
        { id: 2, name: '有机胡萝卜', code: 'P002' },
        { id: 3, name: '有机白菜', code: 'P003' },
        { id: 4, name: '有机土豆', code: 'P004' }
      ])
      
      // 模拟质量检测记录数据
      const qualityRecords = ref([
        {
          id: 'QC001',
          inspectionCode: 'QC20240115001',
          productName: '有机苹果',
          batchNumber: '20240115-001',
          inspectionType: 'routine',
          inspector: '王五',
          inspectionDate: '2024-01-15',
          totalTests: 8,
          overallResult: '合格',
          passRate: '100',
          status: 'completed',
          createTime: '2024-01-15 10:30:00'
        },
        {
          id: 'QC002',
          inspectionCode: 'QC20240115002',
          productName: '有机胡萝卜',
          batchNumber: '20240115-002',
          inspectionType: 'routine',
          inspector: '李四',
          inspectionDate: '2024-01-15',
          totalTests: 6,
          overallResult: '合格',
          passRate: '83.3',
          status: 'completed',
          createTime: '2024-01-15 11:00:00'
        },
        {
          id: 'QC003',
          inspectionCode: 'QC20240115003',
          productName: '有机白菜',
          batchNumber: '20240114-001',
          inspectionType: 'special',
          inspector: '张三',
          inspectionDate: '2024-01-14',
          totalTests: 10,
          overallResult: '不合格',
          passRate: '60',
          status: 'reviewed',
          createTime: '2024-01-14 16:45:00'
        },
        {
          id: 'QC004',
          inspectionCode: 'QC20240115004',
          productName: '有机土豆',
          batchNumber: '20240113-001',
          inspectionType: 'recheck',
          inspector: '赵六',
          inspectionDate: '2024-01-13',
          totalTests: 5,
          overallResult: '待定',
          passRate: '80',
          status: 'processing',
          createTime: '2024-01-13 09:15:00'
        }
      ])
      
      // 统计数据
      const statistics = computed(() => {
        const total = qualityRecords.value.length
        const passed = qualityRecords.value.filter(record => record.overallResult === '合格').length
        const failed = qualityRecords.value.filter(record => record.overallResult === '不合格').length
        const passRate = total > 0 ? ((passed / total) * 100).toFixed(1) : '0'
        
        return {
          total,
          passed,
          failed,
          passRate
        }
      })
      
      // 加载数据
      const loadData = async () => {
        loading.value = true
        
        try {
          await new Promise(resolve => setTimeout(resolve, 1000))
          console.log('正在加载质量检测数据...')
          console.log(`加载完成，共 ${qualityRecords.value.length} 条数据`)
          
          total.value = qualityRecords.value.length
          await nextTick()
        } catch (err) {
          console.error('数据加载失败:', err)
          ElMessage.error('数据加载失败')
        } finally {
          loading.value = false
        }
      }
      
      // 搜索
      const handleSearch = () => {
        currentPage.value = 1
        loadData()
      }
      
      // 重置搜索
      const resetSearch = () => {
        Object.assign(searchForm, {
          inspectionCode: '',
          productName: '',
          inspectionType: '',
          result: '',
          status: '',
          dateRange: []
        })
        currentPage.value = 1
        loadData()
      }
      
      // 显示新增对话框
      const showAddDialog = () => {
        dialogVisible.value = true
      }
      
      // 查看详情
      const viewDetail = (row) => {
        router.push(`/quality/detail/${row.id}`)
      }
      
      // 编辑记录
      const editRecord = (row) => {
        router.push(`/quality/edit/${row.id}`)
      }
      
      // 删除记录
      const deleteRecord = async (row) => {
        try {
          await ElMessageBox.confirm(
            `确定要删除检测记录"${row.inspectionCode}"吗？删除后不可恢复。`,
            '确认删除',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
          
          // 模拟删除请求
          await new Promise(resolve => setTimeout(resolve, 800))
          
          const index = qualityRecords.value.findIndex(record => record.id === row.id)
          if (index > -1) {
            qualityRecords.value.splice(index, 1)
            ElMessage.success('删除成功')
          }
        } catch (error) {
          if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
          }
        }
      }
      
      // 提交表单
      const handleSubmit = async () => {
        try {
          await qualityForm.value.validate()
          submitLoading.value = true
          
          // 模拟提交请求
          await new Promise(resolve => setTimeout(resolve, 800))
          
          ElMessage.success('质量检测记录添加成功')
          dialogVisible.value = false
          loadData()
        } catch (error) {
          console.error('提交失败:', error)
          ElMessage.error('提交失败，请检查输入信息')
        } finally {
          submitLoading.value = false
        }
      }
      
      // 重置表单
      const resetForm = () => {
        if (qualityForm.value) {
          qualityForm.value.resetFields()
        }
        Object.assign(formData, {
          inspectionCode: '',
          inspectionType: '',
          productId: null,
          batchNumber: '',
          inspector: '',
          inspectionDate: ''
        })
      }
      
      // 导出数据
      const exportData = async () => {
        try {
          ElMessage.success('数据导出成功')
          // 这里实现数据导出逻辑
        } catch (error) {
          console.error('导出失败:', error)
          ElMessage.error('导出失败')
        }
      }
      
      // 选择变化
      const handleSelectionChange = (selection) => {
        selectedRecords.value = selection
      }
      
      // 分页处理
      const handleSizeChange = (val) => {
        pageSize.value = val
        loadData()
      }
      
      const handleCurrentChange = (val) => {
        currentPage.value = val
        loadData()
      }
      
      // 获取检测类型标签
      const getInspectionTypeTag = (type) => {
        const typeMap = {
          'routine': '',
          'special': 'warning',
          'recheck': 'info',
          'sampling': 'success'
        }
        return typeMap[type] || ''
      }
      
      // 获取检测类型文本
      const getInspectionTypeText = (type) => {
        const typeMap = {
          'routine': '常规检测',
          'special': '专项检测',
          'recheck': '复检',
          'sampling': '抽检'
        }
        return typeMap[type] || type
      }
      
      // 获取结果类型
      const getResultType = (result) => {
        const resultMap = {
          '合格': 'success',
          '不合格': 'danger',
          '待定': 'warning'
        }
        return resultMap[result] || 'info'
      }
      
      // 获取状态类型
      const getStatusType = (status) => {
        const statusMap = {
          'processing': 'warning',
          'completed': 'success',
          'reviewed': 'info',
          'published': 'primary'
        }
        return statusMap[status] || 'info'
      }
      
      // 获取状态文本
      const getStatusText = (status) => {
        const statusMap = {
          'processing': '进行中',
          'completed': '已完成',
          'reviewed': '已审核',
          'published': '已发布'
        }
        return statusMap[status] || status
      }
      
      // 获取合格率颜色
      const getPassRateColor = (passRate) => {
        const rate = parseFloat(passRate)
        if (rate >= 90) return '#67C23A'
        if (rate >= 70) return '#E6A23C'
        return '#F56C6C'
      }
      
      onMounted(() => {
        loadData()
      })
      
      return {
        loading,
        submitLoading,
        dialogVisible,
        currentPage,
        pageSize,
        total,
        selectedRecords,
        qualityForm,
        searchForm,
        formData,
        rules,
        products,
        qualityRecords,
        statistics,
        loadData,
        handleSearch,
        resetSearch,
        showAddDialog,
        viewDetail,
        editRecord,
        deleteRecord,
        handleSubmit,
        resetForm,
        exportData,
        handleSelectionChange,
        handleSizeChange,
        handleCurrentChange,
        getInspectionTypeTag,
        getInspectionTypeText,
        getResultType,
        getStatusType,
        getStatusText,
        getPassRateColor
      }
    }
  })
  </script>
  
  <style scoped>
  .quality-list {
    padding: 20px;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .header-left h2 {
    margin: 0 0 5px 0;
    color: #2563eb;
  }
  
  .header-left p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
  
  .page-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    padding: 20px;
  }
  
  .search-section {
    margin-bottom: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
  }
  
  .statistics-section {
    margin-bottom: 20px;
  }
  
  .stat-card {
    border: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .stat-content {
    display: flex;
    align-items: center;
    padding: 10px;
  }
  
  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    font-size: 24px;
    color: white;
  }
  
  .stat-icon.total {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
  
  .stat-icon.passed {
    background: linear-gradient(135deg, #67C23A 0%, #85ce61 100%);
  }
  
  .stat-icon.failed {
    background: linear-gradient(135deg, #F56C6C 0%, #f78989 100%);
  }
  
  .stat-icon.rate {
    background: linear-gradient(135deg, #E6A23C 0%, #ebb563 100%);
  }
  
  .stat-info {
    flex: 1;
  }
  
  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 5px;
  }
  
  .stat-label {
    font-size: 14px;
    color: #909399;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    
    .el-button {
      flex-shrink: 0;
      white-space: nowrap;
    }
  }
  
  @media (max-width: 768px) {
    .page-header {
      flex-direction: column;
      gap: 15px;
      align-items: flex-start;
    }
    
    .header-right {
      width: 100%;
      display: flex;
      gap: 10px;
    }
    
    .search-section {
      padding: 15px;
    }
    
    .stat-content {
      flex-direction: column;
      text-align: center;
    }
    
    .stat-icon {
      margin-right: 0;
      margin-bottom: 10px;
    }
  }
  </style> 